package cn.itcast.servlet.review;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.itcast.service.ChapterContentService;
import cn.itcast.service.ChapterService;
import cn.itcast.service.StudentService;
import cn.itcast.service.impl.ChapterContentServiceImpl;
import cn.itcast.service.impl.ChapterServiceImpl;
import cn.itcast.service.impl.StudentServiceImpl;
import cn.itcast.vo.Chapter;
import cn.itcast.vo.ChapterContent;

public class FindChapterContentByChapterId extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		String chapterId = request.getParameter("id");
		String tokenId = request.getParameter("token_id");

		StudentService studentService = new StudentServiceImpl();
		String token_id = studentService.getTokenid(tokenId);

		if (token_id == null) {
			JSONObject obj = new JSONObject();
			try {
				obj.put("status", "fail");
				String json = obj.toString();
				System.out.println(json);
				out.write(json);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {

			ChapterContentService chapterContentService = new ChapterContentServiceImpl();
			List<ChapterContent> list = chapterContentService
					.getChapterContentByChapterId(Integer.parseInt(chapterId));

			JSONObject obj = new JSONObject();
			try {
				obj.put("status", "success");
				JSONArray chapterContents = new JSONArray();
				for (ChapterContent cc : list) {
					JSONObject chapterContent = new JSONObject();
					chapterContent.put("id", cc.getId());
					chapterContent.put("content", cc.getContent());
					chapterContents.put(chapterContent);
				}
				obj.put("chapterContents", chapterContents);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String json = obj.toString();
			System.out.println(json);
			out.write(json);
		}

	}

}
